package com.bakend.modules.chat.websocket.server;

import com.alibaba.fastjson.JSON;
import com.bakend.modules.chat.websocket.entity.C2S_Send2Friend;
import com.bakend.modules.chat.websocket.entity.S2C_FriendNotOnline;
import com.bakend.modules.chat.websocket.entity.S2C_Send2Friend;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ServerEndpoint(value = "/ws/chat/{param}")
@Component
public class WebSocketServer {

    @PostConstruct
    public void init() {
        System.out.println("websocket 加载");
    }

    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    // concurrent包的线程安全Set，用来存放每个客户端对应的Session对象。
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
    private static ConcurrentHashMap<String,Session> usercode2Session = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<Session,String> session2UserCode = new ConcurrentHashMap<>();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        Map<String, String> map = session.getPathParameters();
        String userCode = map.get("param");
        System.out.println("session.getPathParameters()"+map.toString());

//        String str = session.getQueryString();
//        System.out.println("session.getQueryString()"+str);
//
//        String uri = session.getRequestURI().toString();
//        System.out.println("session.getRequestURI().toString()"+uri);
        SessionSet.add(session);
        usercode2Session.put(userCode,session);
        Iterator<Map.Entry<Session, String>> iterator = session2UserCode.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Session, String> next = iterator.next();
            if(next.getValue().equals(userCode)){
                iterator.remove();
            }
        }
        session2UserCode.put(session,userCode);
        int cnt = OnlineCount.incrementAndGet(); // 在线数加1
        log.info("有连接加入，当前连接数为：{}", cnt);
        SendMessage(session, "连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SessionSet.remove(session);
        String userCode = session2UserCode.get(session);
        session2UserCode.remove(session);
        usercode2Session.remove(userCode);
        int cnt = OnlineCount.decrementAndGet();
        log.info("有连接关闭，当前连接数为：{}", cnt);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息：{}",message);
        C2S_Send2Friend c2S_send2Friend = JSON.parseObject(message, C2S_Send2Friend.class);
        String toUser = c2S_send2Friend.getToUser();
        Session friend = usercode2Session.get(toUser);
        if(friend==null){//好友不在线
            S2C_FriendNotOnline response = new S2C_FriendNotOnline(toUser, "好友已经离线");
            SendMessage(session, JSON.toJSONString(response));
            return;
        }
        S2C_Send2Friend response = new S2C_Send2Friend(session2UserCode.get(session), c2S_send2Friend.getMsg());
        SendMessage(friend, JSON.toJSONString(response));//发送好友
        SendMessage(session, message);//原样返回
    }

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误：{}，Session ID： {}",error.getMessage(),session.getId());
        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(String.format("%s (From Server，Session ID=%s)",message,session.getId()));
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     * @param message
     * @throws IOException
     */
    public static void BroadCastInfo(String message) throws IOException {
        for (Session session : SessionSet) {
            if(session.isOpen()){
                SendMessage(session, message);
            }
        }
    }

    /**
     * 指定Session发送消息
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void SendMessage(String message,String sessionId) throws IOException {
        Session session = null;
        for (Session s : SessionSet) {
            if(s.getId().equals(sessionId)){
                session = s;
                break;
            }
        }
        if(session!=null){
            SendMessage(session, message);
        }
        else{
            log.warn("没有找到你指定ID的会话：{}",sessionId);
        }
    }

}
